import { asyncRoutes, constantRoutes } from '@/router'
import { getToken } from '@/utils/auth';

/**
 * Use meta.role to determine if the current user has permission
 * @param route
 */
function hasPermission (route) {
    const hasToken = getToken()
    return !!(hasToken || !(route.meta && route.meta.requireAuth));
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 */
export function filterAsyncRoutes (routes) {
    const res = []
    // console.log(routes, roles)
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children)
            }
            res.push(tmp)
        }
    })
    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = routes.concat(constantRoutes)
        console.log(state.routes)
    }
}

const actions = {
    generateRoutes ({ commit }) {
        return new Promise((resolve, reject) => {
            const accessedRoutes = filterAsyncRoutes(asyncRoutes).concat({
                path: '*',
                redirect: '/404',
                hidden: true
            })
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
